package com.qf.fifter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/10/11 19:28
 */
//gateway的过滤器配置
@Component
public class AuthFifter implements Ordered, GlobalFilter {
    /**
     * 、
     * 过滤器业务
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        获取用户请求中的权限参数
        String token = exchange.getRequest().getQueryParams().getFirst("token");
//如果没有抛出401异常
        if (StringUtils.isEmpty(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
//        如果都满足放行
        return  chain.filter(exchange);
    }

    /*
        当有多个过滤器时,这里定义过滤器顺序
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
